<template>
  <div class="wrapper">
    <div class="header">
      <div class="left">
        <n-space vertical>

          <n-input v-model:value="sqlScript" type="textarea" placeholder="请输入脚本" />
        </n-space>
      </div>
      <div class="right">
        <n-select v-model:value="selectTime" :options="selectTimeOptions" placeholder="选择时间" />
      </div>
      <div class="btn">
        <n-button type="primary" @click="handleQueryClick">查询</n-button>
      </div>
    </div>

    <div ref="chart" style="width: 1000px; height: 400px;"></div>
  </div>
</template>

<script setup>
  import { NButton, NInput, NSpace, NSelect } from 'naive-ui'
  import { ref } from "vue";
  const sqlScript = ref(null);
  const selectTime = ref(null)
  const chart = ref(null);
  const router = useRouter();
  let chartInstance = null;
  const selectTimeOptions = ref([
    {
      label: '1m',
      value: '{ "startTime": 1, "startTimeUnit": "m" }',
    },
    {
      label: '5m',
      value: '{ "startTime": 5, "startTimeUnit": "m" }',
    },
    {
      label: '15m',
      value: '{ "startTime": 15, "startTimeUnit": "m" }',
    }, {
      label: '1h',
      value: '{ "startTime": 1, "startTimeUnit": "h" }',
    }, {
      label: '3h',
      value: '{ "startTime": 5, "startTimeUnit": "h" }',
    }, {
      label: '6h',
      value: '{ "startTime": 6, "startTimeUnit": "h" }',
    }, {
      label: '12h',
      value: '{ "startTime": 12, "startTimeUnit": "h" }',
    }, {
      label: '24h',
      value: '{ "startTime": 24, "startTimeUnit": "h" }',
    }, {
      label: '2d',
      value: '{ "startTime": 2, "startTimeUnit": "d" }',
    }, {
      label: '7d',
      value: '{ "startTime": 7, "startTimeUnit": "d" }',
    }, {
      label: '30d',
      value: '{ "startTime": 7, "startTimeUnit": "d" }',
    },]);

  onMounted(async () => {
    chartInstance = echarts.init(chart.value);
  })

  const handleChartClick = (params) => {
    if (params.componentType === 'series') {
      const xValue = params.name; // x轴的数据
      const yValue = params.value; // y轴的数据
      console.log('X:', xValue, 'Y:', yValue);
      // 跳转到新的页面，并传递数据
      router.push({ path: '/datapoint', query: { x: xValue, y: yValue } });
    }
  };

  async function handleQueryClick() {
    // console.log("handleQueryClick", sqlScript.value, selectTime.value);

    let queryParams = JSON.parse(selectTime.value);
    let sql_data = makeQuery(sqlScript.value, queryParams);
    let csvString = await queryDB(sql_data);
    let csvData = Papa.parse(csvString, {
      header: true,
      skipEmptyLines: true,
      comments: true,
    });

    let option = makeOption(csvData);
    chartInstance.setOption(option);
    // 绑定点击事件
    chartInstance.on('click', handleChartClick);
  }

  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.off('click', handleChartClick);
      console.log('Chart instance disposed'); // 调试信息
    }
  });

</script>

<script>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import * as echarts from 'echarts';
  import { useRouter } from 'vue-router';
  import Papa from 'papaparse';

  import { queryDB } from '../api/api';
  import makeQuery from "@/utils/makeQueryParam"
  import makeOption from '@/utils/echartsOption';

  export default {
    name: 'EChartsLine',
    setup() {
      return;
      const chart = ref(null);
      const router = useRouter();
      let chartInstance = null;


      const handleChartClick = (params) => {
        if (params.componentType === 'series') {
          const xValue = params.name; // x轴的数据
          const yValue = params.value; // y轴的数据
          console.log('X:', xValue, 'Y:', yValue);
          // 跳转到新的页面，并传递数据
          router.push({ path: '/datapoint', query: { x: xValue, y: yValue } });
        }
      };

      onMounted(async () => {
        chartInstance = echarts.init(chart.value);

        let sql_txt = `
  from(bucket: "CPY")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "YS")
  |> filter(fn: (r) => r["_field"] == "WtAvrgINS" or r["_field"] == "WtAvrgISC" or r["_field"] == "WtAvrgOSC")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> map(fn: (r) => ({
    r with 
    _field: if r._field == "WtAvrgINS" then "绝缘层平均厚度"
            else if r._field == "WtAvrgISC" then "内屏层平均厚度"
            else if r._field == "WtAvrgOSC" then "外屏层平均厚度"
            else r._field,
    _value: float(v: r._value), // 确保数值是浮点型
  }))
  |> yield(name: "mean")
  `;
        let queryParams = {
          "startTime": 2,
          "startTimeUnit": "d"
        }

        let sql_data = makeQuery(sql_txt, queryParams);
        let csvString = await queryDB(sql_data);
        let csvData = Papa.parse(csvString, {
          header: true,
          skipEmptyLines: true,
          comments: true,
        });

        let option = makeOption(csvData);
        chartInstance.setOption(option);
        // 绑定点击事件
        chartInstance.on('click', handleChartClick);
      });



      onBeforeUnmount(() => {
        if (chartInstance) {
          chartInstance.off('click', handleChartClick);
          console.log('Chart instance disposed'); // 调试信息
        }
      });

      return {
        chart,
      };
    },
  };
</script>

<style scoped>
  .wrapper {
    border: 2px solid #ccc;
    width: 1000px;
    height: 500px;

    .header {
      height: 100px;
      display: flex;
      justify-content: space-between;
      border: 2px solid #ccc;

      .left {
        width: 50%;
      }

      .right {
        width: 30%;
        border: 2px solid #ccc;
      }

      .btn {
        width: 20%;
      }
    }
  }
</style>